package com.withincode.cascade.models
{
	import flight.mvc.ValueObject;
	
	import mx.collections.ArrayCollection;
	
	[Bindable]
	[RemoteClass(alias="File")]
	public class File extends ValueObject
	{
		public var id:uint;
		public var name:String;
		public var parent:File;
		public var children:ArrayCollection;
		
		
		// Static API
		
		public static function getPath(file:File):String {
			var path:String = file.children ? "/" : "";
			while (file) {
				path = "/" + file.name + path;
				file = file.parent;
			}
			return path;
		}
		
		public static function getFile(path:String):File {
			if (!path)
				return null;
			
			var files:Array = path.replace(/^\/|\/$/g, "").split("/");
			var children:ArrayCollection = CascadeModel.getModel().fileTree;
			if (!children)
				return null;
			
			for (var i:Number = 0; i < files.length; i++) {
				var found:Boolean = false;
				for (var j:Number = 0; j < children.length; j++) {
					var file:File = children[j];
					if (file.name == files[i]) {
						if (i == (files.length - 1))
							return file;
						
						if (file.children != null) {
							found = true;
							children = file.children;
							break;
						} else {
							return null;
						}
					}
				}
				if (!found)
					return null;
			}
			
			return null;
		}
	}
}